package com.synjones.zeuscloudserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.squareup.okhttp.*;
import com.synjones.core.util.IdWorker;
import com.synjones.zeuscloudserver.config.MyConfig;
import com.synjones.zeuscloudserver.mapper.TerminalMapper;
import com.synjones.zeuscloudserver.util.StringUtil;
import com.synjones.zeus.model.ExReqBean;
import com.synjones.zeus.model.ExRespBean;
import com.synjones.zeus.model.StatusInfo;
import com.synjones.zeus.model.config.*;
import com.synjones.zeuscloudserver.service.ConfigService;
import com.synjones.zeuscloudserver.util.ccl.util.G4Utils;
import com.synjones.zeuscloudserver.util.encrypt.DigestUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

import static com.synjones.zeus.model.CodeStr.SUCCESSCODE;
import static com.synjones.zeus.model.config.RequestCommonParams.*;

/**
 * @author yys
 * Description:
 * @date created in 15:32 2018-04-13
 * Modified by:
 */
@Service
public class ConfigServiceImpl implements ConfigService {
    private static final Logger logger = LoggerFactory.getLogger(ConfigServiceImpl.class);
    @Resource
    private MyConfig myConfig;
    @Resource
    private TerminalMapper terminalMapper;
    /**
     *  获取配置信息
     *  @param reqBean
     *  @author yys
     *  Description: 获取配置信息
     *  @date 12:23 2018-07-04
     *  @return ExRespBean<ConfigRespBean>
     *  throws
     */
    @Override
    public ExRespBean<ConfigRespBean> getConfig(ExReqBean<ConfigReqBean> reqBean) {
        Long start = System.currentTimeMillis();
        ExRespBean<ConfigRespBean> result;
        List<SchoolBean> listSchool;
        Map map = new HashMap(7);
        map.put("access_token",myConfig.getAccessToken());
        map.put("charset","utf-8");
        map.put("req_date",String.valueOf(G4Utils.getCurrentTimeAsNumber()));
        map.put("format","json");
        map.put("nonce",String.valueOf(new IdWorker(0).nextId()));
        map.put("http_verb","post");
        map.put("url",myConfig.getConfigUrl());
        String temp = reqConfigSvcByPost(map,myConfig.getConfigUrl());
        String[] organizationCodes = myConfig.getOrganizationCode().split(",");
        JSONObject json = JSONObject.fromObject(temp);
        Map mapConfig = JSON.parseObject(json.getString("config"));
        listSchool = new ArrayList<>();
        for(String orgCode : organizationCodes){
            if(G4Utils.isNotEmpty(mapConfig.get(orgCode + "_name"))){
                SchoolBean schoolBean = new SchoolBean(String.valueOf(mapConfig.get(orgCode + "_name")),String.valueOf(mapConfig.get(orgCode + "_organizationCode")),
                        String.valueOf(mapConfig.get(orgCode + "_ip")),String.valueOf(mapConfig.get(orgCode + "_port")));
                listSchool.add(schoolBean);
            }
        }
        List<TerminalTypeBean> listTerminalType = terminalMapper.getTerminalTypeList();
        ConfigRespBean configRespBean = new ConfigRespBean(listSchool,listTerminalType);
        configRespBean.setSchool(listSchool);
        configRespBean.setTerminal(listTerminalType);
        result = new ExRespBean<>();
        result.setErrCode(SUCCESSCODE);
        result.setErrMsg(StatusInfo._6001.desc());
        result.setTipMsg(StatusInfo._6001.desc());
        result.setData(configRespBean);
        Long end = System.currentTimeMillis();
        logger.info("处理时间为：" + (end - start) + "毫秒");
        return result;
    }

    private String reqConfigSvcByPost(Map<String, String> map, String url) {
        RequestBody formBody = new FormEncodingBuilder()
                .add(StringUtil.isNullOrEmpty(map.get(REQ_DATE))?"":REQ_DATE, StringUtil.isNullOrEmpty(map.get(REQ_DATE))?"":map.get(REQ_DATE))
                .add(StringUtil.isNullOrEmpty(map.get(CHARSET))?"":CHARSET, StringUtil.isNullOrEmpty(map.get(CHARSET))?"":map.get(CHARSET))
                .add(StringUtil.isNullOrEmpty(map.get(FORMAT))?"":FORMAT, StringUtil.isNullOrEmpty(map.get(FORMAT))?"":map.get(FORMAT))
                .add(StringUtil.isNullOrEmpty(map.get(NONCE))?"":NONCE, StringUtil.isNullOrEmpty(map.get(NONCE))?"":map.get(NONCE))
                .build();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .header(SYN_SIGNATURE, getSign(map))//将签名放入请求的头部
                .post(formBody)
                .build();
        String doGet = doRequestConfigSvc(client,request);
        return doGet;
    }
    private String getSign(Map<String, String> map){
        String app_id = map.get(URL).split("/")[4];
        map.put(APP_ID, app_id);
        String charset = map.get(CHARSET);
        String signText = StringUtil.getSortedValue(map);
        logger.info("***************signText={}", signText);
        String sign="";
        try {
            sign = StringUtil.isNullOrEmpty(charset)?
                    DigestUtil.hmacSha1(signText, myConfig.getHmacKey()):DigestUtil.hmacSha1(signText, myConfig.getHmacKey(),charset);
        } catch (UnsupportedEncodingException ex) {
        }
        logger.info("***************sign={}", sign);
        return sign;
    }

    private String doRequestConfigSvc(OkHttpClient client,Request request){
        String returnStr = null;
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                returnStr = response.body().string();
            }
        } catch (IOException ex) {
            logger.error("***************doPost error>>>>>>>>>>>>>>>>{}", ex);
        }
        return returnStr;
    }
}
